問題描述
過濾從 Wagtail 核心頁面導入的多個模型的自定義字段 (Filter on custom field across multiple models that import from Wagtail core Page)
我有兩個自定義 Page
模型共享一個共同的字段,例如:
class CustomPageModelOne(Page):
custom_field = models.IntegerField()
...
class CustomPageModelTwo(Page):
custom_field = models.IntegerField()
...
理想情況下,我需要跨兩種自定義類型運行單個過濾器頁面
模型。Wagtail 文檔說我可以使用 exact_type
方法來指定從核心 Page
繼承的多個模型,所以我正在嘗試以下一些變體:
Page.objects.exact_type(CustomPageModelOne, CustomPageModelTwo).filter(custom_field=123)
但是,當我嘗試過濾使用這兩種模型的任何 QuerySet 時,我收到一個錯誤:
django.core.exceptions.FieldError: Cannot resolve keyword 'custom_field' into field。
如何跨多個共享一個字段的 Wagtail 自定義頁面模型進行查詢?
注意:
參考解法
方法 1:
As you do Page.objects...
you can only filter on fields of the Page model and subclasses of Page
To filter specifically on fields of your CustomPageModelOne
, you would have to use CustomPageModel.objects...
where that model has that field and both your custom page models are subclasses from
方法 2:
Apparently Page.objects.exact_type
is only returning a queryset based upon Page
, which makes sense because exact_type
has no way of knowing what fields would occur on models descended from Page
. I would suggest the following as an alternative approach if re‑architecting your models is not an option:
from itertools import chain
model_one_results = CustomPageModelOne.objects.filter(custom_field=123)
model_two_results = CustomPageModelTwo.objects.filter(custom_field=123)
all_results = list(chain(model_one_results, model_two_results))
(by Brylie Christopher Oxley、Vincent、Dan Swain)